#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sqlite3
import os
import traceback
import json

#数据库文件绝对路径
PROJECT_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../../")
DB_PATH = os.path.join(PROJECT_PATH,"db")
DB_FILE_PATH = DB_PATH + "\\mitm.db"

def get_conn(path):
    conn = sqlite3.connect(path)
    if os.path.exists(path) and os.path.isfile(path):
        return conn
    else:
        conn = None
        return sqlite3.connect(':memory:')
def get_cursor(conn):
    if conn is not None:
        return conn.cursor()
    else:
        return get_conn('').cursor()
def mitm_get_cur(path):
    conn = get_conn(path)
    cu = get_cursor(conn)
    return conn,cu
def close_all(conn, cu):
    '''关闭数据库游标对象和数据库连接对象'''
    try:
        if cu is not None:
            cu.close()
    finally:
        if conn is not None:
            conn.close()
#获得最近的头信息
def mitm_get_headers_by_system_name(table,systemName):
    rows = mitm_select_max_data(table,"system_name",systemName,"headers")
    result = {}
    if table == 'mitmhttp':
        if len(rows)>0:
            for r in rows:
                result = eval(r[0])
    elif table == 'mitm_rep_info':
        if len(rows)>0:
            for r in rows:
                result = eval(r[0])
    return result
#最大值
def mitm_select_max_data(table,field,value,maxField):
    sql = '''select '''+maxField+''' from '''+table+''' where '''+field+''' = ? order by id desc limit 1'''
    data = (value,)
    conn,cu = mitm_get_cur(DB_FILE_PATH)
    cu.execute(sql,data)
    r = cu.fetchall()
    close_all(conn,cu)
    return r

#获得指定请求信息
def mitm_get_req_info_by_url(table,url):
    rows = mitm_select_max_data(table,"url",url,"method,url,headers,params")
    result = {}
    if table == 'mitmhttp':
        if len(rows)>0:
            for r in rows:
                result['method'] = r[0]
                result['url'] = r[1]
                result['headers'] = eval(r[2])
                result['params'] = r[3]
    elif table == 'mitm_rep_info':
        if len(rows)>0:
            for r in rows:
                result['method'] = r[0]
                result['url'] = r[1]
                result['headers'] = eval(r[2])
                result['params'] = r[3]
    return result
